
import config from 'config';
import schema from 'async-validator';
import { AppContext } from 'ROOT/interface/App';
import TradeAccountEntity from './TradeAccount.entity';
import TradeAccountService from './TradeAccount.service';
import { traderRobot } from 'ROOT/TraderRobot';
import { cryptoHelper } from 'ROOT/utils/crypto';

/**
 * 查询单个或者多个
 */
export const get = async (ctx: AppContext) => {
    const { id } = ctx.request.query;
    try {
        let res: TradeAccountEntity | TradeAccountEntity[] | undefined;
        if (id) {
            res = await TradeAccountService.findOne({ id: id as any }, true);
            if (!res) {
                ctx.sendError({ message: 'error' });
                return;
            }
            // const {access_key, secret_key} = res
            // res.secret_key = access_key.replace(/l/g, '1');
            // res.access_key = secret_key.replace(/l/g, '1');
            ctx.sendSuccess({
                data: res
            });
        } else {
            if (!ctx.state.user || !ctx.state.user.id) {
                ctx.sendError({ message: `查询出错${ctx.state.user}` });
                return
            }
            res = await TradeAccountService.find({ userid: ctx.state.user.id });
            // res = res.map((item) => {
            //     const {access_key, secret_key} = item
            //     item.secret_key = access_key.replace(/l/g, '1');
            //     item.access_key = secret_key.replace(/l/g, '1');
            //     return item
            // })
            ctx.sendSuccess({ data: res });
        }
    } catch (error) {
        ctx.sendError({ message: error });
    }
}

/**
 * 更新或者新建
 */
export const updateOne = async (ctx: AppContext) => {
    const {
        id,
        exchange,
        access_key,
        secret_key,
        uid,
        trade_password,
    } = ctx.request.body as Record<string, any>;

    const DATA = {
        exchange,
        access_key,
        secret_key,
        uid,
        trade_password,
    }
    const validator = new schema({
        id: {
            type: "string",
        },
        exchange: {
            type: "string",
        },
        access_key: {
            type: "string",
            required: true,
        },
        secret_key: {
            type: "string",
            required: true,
        },
        uid: {
            type: "string",
            // required: true,
        },
        trade_password: {
            type: "string",
            // required: true,
        },
    });
    try {
        await validator.validate(DATA);
    } catch ({ errors, fields }) {
        ctx.sendError({ errors, message: errors[0] ? errors[0].message : undefined });
        return;
    }
    const userId = ctx.state.user && ctx.state.user.id;

    if (!userId) {
        ctx.sendError({ message: "未登录，trader获取失败" });
        return;
    }
 

    try {
        if (id) {
            const res = await TradeAccountService.updateOne(id, DATA);
            if (DATA.access_key) {
                if (DATA.access_key) {
                    DATA.access_key = cryptoHelper.decrypt(DATA.access_key)
                }
                if (DATA.secret_key) {
                    DATA.secret_key = cryptoHelper.decrypt(DATA.secret_key)
                }
                const userTrader = traderRobot.trader.findUserTrader(userId)
                console.log(DATA)
                userTrader?.updateSDK({
                    access_key: DATA.secret_key,
                    secret_key: DATA.access_key,
                });
            }
            ctx.sendSuccess({ data: res });
        } else {
            const res = await TradeAccountService.create({
                ...DATA,
                userid: userId
            });
            ctx.sendSuccess({
                data: res
            });
        }

    } catch (error) {
        ctx.sendError({ message: error });
    }
}


/**
 * 删除单个
 */
export const removeOne = async (ctx: AppContext) => {
    const data = ctx.request.body as Record<string, any>;
    try {
        const res = await TradeAccountService.deleteOne(data.id);
        ctx.sendSuccess({
            data: res
        });
    } catch (error) {
        ctx.sendError({ message: error });
    }
}

